package com.yupi.yu_picture.service.impl;
import java.awt.*;
import java.io.IOException;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yu_picture.api.aliyunai.model.ALiYunAiApi;
import com.yupi.yu_picture.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.yupi.yu_picture.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.yupi.yu_picture.exception.BusinessException;
import com.yupi.yu_picture.exception.ErrorCode;
import com.yupi.yu_picture.exception.ThrowUtil;
import com.yupi.yu_picture.manager.CosManager;
import com.yupi.yu_picture.manager.FileManager;
import com.yupi.yu_picture.manager.upload.FilePictureUpload;
import com.yupi.yu_picture.manager.upload.PictureUploadTemplate;
import com.yupi.yu_picture.manager.upload.UrlPictureUpload;
import com.yupi.yu_picture.model.dto.file.UploadPictureResult;
import com.yupi.yu_picture.model.dto.picture.*;
import com.yupi.yu_picture.model.entity.Picture;
import com.yupi.yu_picture.model.entity.Space;
import com.yupi.yu_picture.model.entity.User;
import com.yupi.yu_picture.model.enums.PictureReviewStatusEnum;
import com.yupi.yu_picture.model.vo.PictureVO;
import com.yupi.yu_picture.model.vo.UserVO;
import com.yupi.yu_picture.service.PictureService;
import com.yupi.yu_picture.mapper.PictureMapper;
import com.yupi.yu_picture.service.SpaceService;
import com.yupi.yu_picture.service.UserService;
import com.yupi.yu_picture.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 41722
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-03-22 22:24:49
*/
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService{

    @Resource
    FileManager fileManager;
    @Resource
    CosManager cosManager;
    @Resource
    UserService userService;
//    @Resource
//    PictureService pictureService;
    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private ALiYunAiApi aLiYunAiApi;

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        ThrowUtil.throwIf(loginUser==null, ErrorCode.NO_AUTH_ERROR);

        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtil.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//            // 必须空间创建人（管理员）才能上传
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
//            }
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }


        Long pictureId = null;//通过图片id去添加或者说更新数据库中的图片
        if(pictureUploadRequest!=null){
            pictureId=pictureUploadRequest.getId();
        }
        //如果是更新图片，查看图片是否存在
        if(pictureId!=null){
            Picture oldPicture = this.getById(pictureId);
            ThrowUtil.throwIf(oldPicture==null,ErrorCode.NOT_FOUND_ERROR,"图片不存在");
//            //仅本人和管理员可以编辑更新
//            if (loginUser.getId()!=oldPicture.getUserId() && !userService.isAdmin(loginUser)){
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//            }
            //校验空间id是否一致
            if (spaceId==null){
                if(oldPicture.getSpaceId()!=null) {
                    spaceId = oldPicture.getSpaceId();
                }
            }else{
                if (ObjUtil.notEqual(spaceId,oldPicture.getSpaceId())){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间id不一致");
                }
            }

        }
        //上传图片，并得到图片信息
        //按照用户id划分目录
        String uploadPathPrefix=null;
        if (spaceId==null){
            uploadPathPrefix= String.format("public/%s",loginUser.getId());
        }else {
            uploadPathPrefix=String.format("space/%s",spaceId);
        }

        PictureUploadTemplate pictureUploadTemplate=filePictureUpload;
        if (inputSource instanceof String){
            pictureUploadTemplate=urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);


        //构造要入库的图片信息
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        String picName=uploadPictureResult.getPicName();
        if (pictureUploadRequest!=null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())){
            picName=pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setPicColor(uploadPictureResult.getPicColor());

        picture.setUserId(loginUser.getId());

        picture.setSpaceId(spaceId);

        this.fillReviewParams(picture, loginUser);

        if (pictureId!=null){
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }

        Long finalSpaceId=spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtil.throwIf(!result,ErrorCode.OPERATION_ERROR,"图片上传失败");
            if(finalSpaceId!=null){
                boolean update = spaceService.lambdaUpdate().eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount +1")
                        .update();
                ThrowUtil.throwIf(!update,ErrorCode.OPERATION_ERROR,"额度更新失败");
            }
            return picture;
        });
        boolean result = this.saveOrUpdate(picture);
        ThrowUtil.throwIf(!result,ErrorCode.OPERATION_ERROR,"图片上传失败");
        return PictureVO.objToVo(picture);


    }


    @Override
    public QueryWrapper<Picture> getPictureQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> pictureQueryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest==null){
            return pictureQueryWrapper;
        }
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();



        //serarchText 支持从name跟introduction中检索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            pictureQueryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }

        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        pictureQueryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        pictureQueryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        pictureQueryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        pictureQueryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);


        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        pictureQueryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        pictureQueryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        pictureQueryWrapper.isNull(nullSpaceId, "spaceId");
        pictureQueryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        pictureQueryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                pictureQueryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        pictureQueryWrapper.orderBy(ObjUtil.isNotEmpty(sortField),sortOrder.equals("ascend"),sortField);
        return pictureQueryWrapper;

    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVo(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }



    @Override
    public  List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser){
        ThrowUtil.throwIf(spaceId==null||picColor==null,new BusinessException(ErrorCode.PARAMS_ERROR));
        ThrowUtil.throwIf(loginUser==null,new BusinessException(ErrorCode.NOT_LOGIN_ERROR));
        Space space = spaceService.getById(spaceId);
        ThrowUtil.throwIf(space==null,new BusinessException(ErrorCode.PARAMS_ERROR,"空间不存在"));
        if (!space.getUserId().equals(loginUser.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有空间访问权限");
        }
        //1.把空间里所有有这个主色调的图片查出来
        List<Picture> pictureList = this.lambdaQuery().eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();

        if (CollUtil.isEmpty(pictureList)){
            return Collections.emptyList();
        }
        //将目标颜色转成color对象
        Color targetColor = Color.decode(picColor);
        //2.按照相似度排序，取前十二个
        List<Picture> sortedPictures = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    String hexColor = picture.getPicColor();
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                })).limit(12)
                .collect(Collectors.toList());
        //3.将图片转成vo返回给前端

        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());

    }




    @Override
    public Page<PictureVO> getPictureVoPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> picturePageRecords = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(),picturePage.getSize(),picturePage.getTotal());
        if (CollUtil.isEmpty(picturePageRecords)){
            return pictureVOPage;
        }
        List<PictureVO> pictureVOList = picturePageRecords.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        List<Long> userIdList = picturePageRecords.stream().map(Picture::getUserId).collect(Collectors.toList());
        Map<Long, List<User>> userIdListMap = userService.listByIds(userIdList).stream().collect(Collectors.groupingBy(User::getId));

        pictureVOList.forEach(pictureVO -> {
            long userId=pictureVO.getUserId();
            User user=null;
            if (userIdListMap.containsKey(userId)){
                user=userIdListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVo(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    //编写校验图片方法，用于更新和修改图片时进行判断
    @Override
    public void validPicture(Picture picture){
        ThrowUtil.throwIf(picture==null,ErrorCode.PARAMS_ERROR);
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        ThrowUtil.throwIf(ObjUtil.isNull(id),ErrorCode.PARAMS_ERROR,"id不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtil.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtil.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }

    }

    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        //在业务层可以实现
        ThrowUtil.throwIf(pictureReviewRequest==null,ErrorCode.PARAMS_ERROR);
        ThrowUtil.throwIf(loginUser==null,ErrorCode.NOT_LOGIN_ERROR);

        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        String reviewMessage = pictureReviewRequest.getReviewMessage();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (id==null||reviewStatusEnum==null||PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)){
            //如果没有传图片id 或者 传过来的转台参数不符合枚举参数，或者已经是待审核状态就抛出异常
            new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Picture oldPicture = this.getById(id);
        ThrowUtil.throwIf(oldPicture==null,ErrorCode.NOT_FOUND_ERROR);

        if (oldPicture.getReviewStatus().equals(reviewStatus)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请勿重复提交审核");
        }

        Picture newPicture = new Picture();
        BeanUtils.copyProperties(oldPicture,newPicture);
        newPicture.setReviewStatus(reviewStatus);
        newPicture.setReviewMessage(reviewMessage);

        //操作数据库
        boolean result = this.updateById(newPicture);
        ThrowUtil.throwIf(!result,ErrorCode.OPERATION_ERROR);


    }

    @Override
    public void fillReviewParams(Picture picture, User user) {
        if (userService.isAdmin(user)){
            //管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewMessage("管理员自动过审");
            picture.setEditTime(new Date());
            picture.setReviewerId(user.getId());
        }else{
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
     String searchText = pictureUploadByBatchRequest.getSearchText();
     //格式化数量
     Integer count = pictureUploadByBatchRequest.getCount();
    ThrowUtil.throwIf(count>30,ErrorCode.PARAMS_ERROR,"抓取数量最多三十条");
    //要抓取的地址：https://cn.bing.com/images/async?q=%s&mmasync=1
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document=null;
        try {
            document = Jsoup.connect(fetchUrl).get();
            
        } catch (IOException e) {
            log.error("页面获取失败",e);
            throw new RuntimeException(e);
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount=0;
        for (Element imgElement:imgElementList){
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)){
                log.info("当前连接为空，已跳过：{}",fileUrl);
                continue;
            }
            //处理上传图片地址，防止出现转义
            int questionMarkIndex = fileUrl.indexOf('?');
            if (questionMarkIndex>-1){
                fileUrl=fileUrl.substring(0,questionMarkIndex);
            }
            String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
            if (StrUtil.isBlank(namePrefix)) {
                namePrefix=searchText;
            }
            //上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            if (StrUtil.isNotBlank(namePrefix)){
                pictureUploadRequest.setPicName(namePrefix+(uploadCount+1));
            }
            try{
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功，id={}",pictureVO.getId());
                uploadCount++;
            }catch (Exception e){
                log.error("图片上传失败",e);
                continue;
            }
            if (uploadCount>=count){
                break;
            }
        }
        return uploadCount;
    }
    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }
        // FIXME 注意，这里的 url 包含了域名，实际上只要传 key 值（存储路径）就够了
        cosManager.deleteObject(oldPicture.getUrl());
        // 清理缩略图
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            cosManager.deleteObject(thumbnailUrl);
        }

    }

    @Override
    public void  checkPictureAuth(User loginUser, Picture picture){
        Long spaceId = picture.getSpaceId();
        if (spaceId==null){
            if (!picture.getUserId().equals(loginUser.getId())&&userService.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }else{
            if (!picture.getUserId().equals(loginUser.getId())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    @Override
    public void deletePicture(User loginUser, Long pictureId) {
        ThrowUtil.throwIf(loginUser==null,ErrorCode.NO_AUTH_ERROR);
        ThrowUtil.throwIf(pictureId<=0,ErrorCode.PARAMS_ERROR);
        Picture oldPicture = this.getById(pictureId);
        ThrowUtil.throwIf(oldPicture==null,ErrorCode.NOT_FOUND_ERROR);
        //checkPictureAuth(loginUser,oldPicture);


        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtil.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtil.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 异步清理文件
        this.clearPictureFile(oldPicture);
    }

    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtil.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        //checkPictureAuth(loginUser, oldPicture);
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtil.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser){
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();



        //1.校验参数
        ThrowUtil.throwIf(spaceId==null||CollUtil.isEmpty(pictureIdList),ErrorCode.PARAMS_ERROR);
        ThrowUtil.throwIf(loginUser==null,ErrorCode.NO_AUTH_ERROR);
        //2.校验空间权限
        Space space = spaceService.getById(spaceId);
        if (space==null){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"空间不存在");
        }
        if (!space.getUserId().equals(loginUser.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间操作权限");
        }
        //3.查询指定图片，仅选择需要的字段
        List<Picture> pictureList = this.lambdaQuery().select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();

        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList,nameRule);
        //4.更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)){
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)){
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });


        //5.批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtil.throwIf(!result,ErrorCode.OPERATION_ERROR);


    }



    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList)||StrUtil.isBlank(nameRule)){
            return ;
        }
        long count=1;//从一递增重命名
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        }catch (Exception e){
            log.error("名称解析错误",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"名称解析错误");
        }
    }


    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验
        //checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aLiYunAiApi.createOutPaintingTask(taskRequest);
    }

}






